import { Component, OnInit } from '@angular/core';
import { Sentence } from './../../model/sentence';
import { SentenceService } from './../../service/sentence.service';
import { Location } from '@angular/common';
import { ToastService } from 'src/app/service/toast.service';
import { LoadingController } from '@ionic/angular';
@Component({
  selector: 'app-modification',
  templateUrl: './modification.page.html',
  styleUrls: ['./modification.page.scss'],
})
export class ModificationPage implements OnInit {
  public isDirty = false;
  public sentence: Sentence = { englishText: '', chineseText: '' } as Sentence;

  private oldEnglishText: string;
  private oldChineseText: string;

  constructor(
    private sentenceService: SentenceService,
    private toastService: ToastService,
    private location: Location,
    private loadingCtrl: LoadingController
  ) {}

  ngOnInit(): void {}
  ionViewWillEnter() {
    this.sentence = this.location.getState() as Sentence;
    this.oldChineseText = this.sentence.chineseText;
    this.oldEnglishText = this.sentence.englishText;
  }
  public async save() {
    const loading = await this.loadingCtrl.create({
      message: '数据处理...',
    });
    await loading.present();
    this.sentenceService.modify(this.sentence).subscribe((n) => {
      this.toastService.showInfo('保存成功');
      loading.dismiss();
      history.back();
    });
  }

  public change(event) {
    if (
      this.oldChineseText !== this.sentence.chineseText ||
      this.oldEnglishText !== this.sentence.englishText
    ) {
      this.isDirty = true;
    } else {
      this.isDirty = false;
    }
  }
}
